package com.xbongbong.paas.log;

import com.xbongbong.paas.toolbox.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

/**
 * mongo查询条件集合
 * @author kaka
 * @date 2019/1/21 13:53
 * @since v1.0
 * @version v1.0
 */
@Setter
@Getter
@ToString
public class MongoQueryConditions {

    /**
     * 默认分页条数
     */
    public static final Integer DEFAULT_LIMIT = 15;

    /**
     * mongo skip,对应mysql limit x,y 第一个参数x
     */
    private Integer skip;

    /**
     * mongo limit, 对应mysql limit x,y第二个参数y
     */
    private Integer limit;

    /**
     * 为了表示corpid的特殊性，将corpid提出来
     */
    private String corpid;

    /**
     * 排序字段
     */
    private List<String> sorts;

    /**
     * 条件列表
     */
    private List<MongoQueryItem> conditions;

    public MongoQueryConditions() {
        conditions = new ArrayList<>();
        sorts = new ArrayList<>();
    }

    public MongoQueryConditions(Integer skip, Integer limit, List<MongoQueryItem> conditions) {
        this.skip = skip;
        this.limit = limit;
        this.conditions = conditions;
        this.sorts = new ArrayList<>();
    }

    public MongoQueryConditions(Integer skip, Integer limit) {
        this(skip, limit, new ArrayList<MongoQueryItem>());
    }

    public MongoQueryConditions(Integer limit) {
        this(0, limit);
    }

    public void addCondition(MongoQueryItem item) {
        this.conditions.add(item);
    }

    public void addSortItem(String orderByItem) {
        if(!StringUtil.isEmpty(orderByItem)) {
            this.sorts.add(orderByItem);
        }
    }

    public void formatOrderByStr(String orderByStr) {
        if(StringUtil.isEmpty(orderByStr)) {
           return;
        }
        String[] orderByItems = orderByStr.split(",");
        for(String orderByItem : orderByItems) {
            addSortItem(orderByItem);
        }
    }

    public Integer getSkip() {
        if(skip == null || skip < 0) {
            skip = 0;
        }
        return skip;
    }

    public Integer getLimit() {
        if(limit == null || limit < 0) {
            limit = DEFAULT_LIMIT;
        }
        return limit;
    }
}
